<template>
  <div class='upload' :style="{background: `url(${backgroundImg})`,'background-size': 'cover'}">
    <div class='uploadmodule'>
      <div class='uploadbox'>
        <van-image round :src='headportrait'
        alt='上传头像' class='headimg' />
        <van-icon name="printer" @click='fakeUpload' />
          <input
            @change='realUpload'
            type='file'
            ref='fileupload'
            accept='.jpg, .jpeg, .png'
            class='hidden-input'
          />
      </div>
    </div>

    <!-- 未登录 -->
    <div class='islogin' v-if='!determinethelogin'>
      <van-button
        color='linear-gradient(to right, #4bb0ff, #6149f6)'
        :to="{ name: 'User-type', params: { type: 'login' } }"
      >
        立即登录
      </van-button>
      <van-button
        color='linear-gradient(to right, #4bb0ff, #6149f6)'
        :to="{ name: 'User-type', params: { type: 'register' } }">
        马上注册
      </van-button>
    </div>

    <!-- 已登录 -->
    <div class='userinfo' v-if='determinethelogin'>
      <div class='emptybox'></div>
      <div class='infotext'>
        <div class='infoname'>{{ userinfos.username }}</div>
        <div class='ratebox'>
          <van-rate
            v-model='value'
            readonly
            allow-half
            void-icon='star'
            void-color='#000'
          />
        </div>
        <div class='signaturebox'>
          <van-icon name='records' size='.3rem' />
          <span>{{ userinfos.signature }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import http from '@/utils/axios'
// import http from 'axios'
import Vue from 'vue'
import { Icon, Image, Button, Rate, Toast } from 'vant'
Vue.use(Icon).use(Image).use(Button).use(Rate).use(Toast)

export default {
  data () {
    return {
      headportrait: require('../assets/headimg.jpg'),
      backgroundImg: require('@/assets/images/bg.6837f67.png'),
      determinethelogin: false,
      userinfos: {},
      value: 2.5
    }
  },
  mounted () {
    let token = ''
    // 先数据库,再默认头像
    if (sessionStorage.userInfo) {
      token = JSON.parse(sessionStorage.userInfo).token
      if (token) {
        this.determinethelogin = true
        http.post('/vant/userinfo', { token }).then(res => {
          if (res.data.code === 200) {
            // console.log(res)
            this.userinfos.username = '用户: ' + res.data.result.username
            this.userinfos.signature = '个性签名'
          }
        })

        http.post('/vant/getavatar', {
          token
          // 不用写data
        }).then(
          res => {
            if (res.data.code === 200) {
              const path = res.data.avatar
              this.setpath(path)
            }
          },
          err => {
            console.log(err)
          }
        )
      }
    }
  },
  methods: {
    fakeUpload () {
      // 触发input的事件
      if (sessionStorage.userInfo) {
        if (JSON.parse(sessionStorage.userInfo).token) {
          this.$refs.fileupload.click()
        }
      }
    },
    realUpload () {
      const file = this.$refs.fileupload.files[0]
      // 表单 - name属性就是表单对象的key
      // 原生js生成表单对象
      const formData = new FormData()
      // 转化成二进制
      formData.append('avatar', file)

      if (sessionStorage.userInfo) {
        // const AUTH_TOKEN = JSON.parse(sessionStorage.userInfo).token
        // Form Date: {avatar: (binary)}
        http({
          url: '/vant/upload-avatar',
          method: 'POST',
          data: formData,
          contentType: false, // 避免jq
          processData: false // 不转换data格式
          // headers: {
          //   Authorization: AUTH_TOKEN
          //   // 'Content-Type': 'application/x-www-form-urlencoded'
          // }
        }).then(res => {
          if (res.data.code === 200) {
            this.setpath(res.data.avatar)
          }
        },
        err => {
          console.log(err)
        })
      }
    },
    setpath (url) {
      // http://localhost:3000/avatar/1579531184079-user-a-a1.jpg
      if (url) {
        url = url.replace(/public/, '')
        this.headportrait = url
      } else {
        Toast('获取头像地址失败')
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.upload {
  height: 3rem;
  background-color: #fff;
  .uploadmodule {
    height: 100%;
    width: 40vw;
    float: left;
    .uploadbox {
      margin-top: .35rem;
      margin-left: 7vw;
      width: 25vw;
      text-align: center;
      .headimg {
        width: 2rem;
        height: 2rem;
        border-radius: 50%;
        margin: 0 auto
      }
      .hidden-input {
          display: none;
      }
    }
  }
  .userinfo {
    width: 60vw;
    height: 100%;
    float: right;
    .emptybox {
      width: 10vw;
      height: 100%;
      float: left;
    }
    .infotext {
      float: left;
      width: 50vw;
      height: 100%;
      text-align: left;
      .infoname {
        font-weight: normal;
        font-size: 0.4rem;
        margin-top: .4rem;
      }
      .ratebox {
        margin-top: .3rem;
      }
      .signaturebox {
        margin-top: .1rem;
        i{
          vertical-align: middle;
        }
        span {
          font-size: 0.3rem;
          line-height: .5rem;
        }
      }
    }
  }
  .islogin {
    width: 60vw;
    height: 100%;
    float: right;
    button {
      margin: 1rem 0 0 .2rem;
    }
  }
}
</style>
